import React, { createContext, useContext, useMemo, useState, useEffect } from 'react';

type Messages = Record<string, string>;
type Locale = 'en' | 'zh' | 'vi';

type I18nContextValue = {
  locale: Locale;
  setLocale: (l: Locale) => void;
  t: (key: string) => string;
};

const I18nContext = createContext<I18nContextValue | undefined>(undefined);

// 静态导入翻译文件
import zhMessages from './zh.json';
import enMessages from './en.json';
import viMessages from './vi.json';

const messages: Record<Locale, Messages> = {
  zh: zhMessages,
  en: enMessages,
  vi: viMessages,
};

const loadMessages = async (locale: Locale): Promise<Messages> => {
  try {
    return messages[locale] || {};
  } catch (error) {
    console.warn(`Failed to load messages for locale: ${locale}`, error);
    return {};
  }
};


export const I18nProvider: React.FC<{ defaultLocale?: Locale }> = ({ defaultLocale = 'zh', children }) => {
  const [locale, setLocale] = useState<Locale>(defaultLocale);
  const [messages, setMessages] = useState<Messages>({});

  useEffect(() => {
    loadMessages(locale).then(setMessages);
  }, [locale]);

  const t = useMemo(() => (key: string) => messages[key] ?? key, [messages]);
  const value = useMemo(() => ({ locale, setLocale, t }), [locale, t]);
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
};

export function useI18n() {
  const ctx = useContext(I18nContext);
  if (!ctx) throw new Error('useI18n must be used within I18nProvider');
  return ctx;
}



